
package com.sm.shoplook.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.sm.shoplook.config.ProjectProperties;
import com.sm.shoplook.constant.ResultMessage;
import com.sm.shoplook.vo.base.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author chenpy-1072
 * @desc 阿里云短信
 * @date 2018/9/8 17:49
 * @see
 */
@Component
public class SMSUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(SMSUtil.class);
	@Autowired
	private ProjectProperties projectProperties;

	public ApiResult<String> sendSms(String phoneNums, String templateCode, Map<String, Object> paramMap) {
		try {
			System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
			System.setProperty("sun.net.client.defaultReadTimeout", "10000");
			final String product = "Dysmsapi";
			final String domain = "dysmsapi.aliyuncs.com";
			// 替换成你的AK
			final String accessKeyId = projectProperties.getAliSms().getAccessKeyId();
			final String accessKeySecret = projectProperties.getAliSms().getAccessKeySecret();
			// 初始化ascClient,暂时不支持多region（请勿修改）
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
			IAcsClient acsClient = new DefaultAcsClient(profile);
			SendSmsRequest request = new SendSmsRequest();
			request.setMethod(MethodType.POST);
			request.setPhoneNumbers(phoneNums);
			request.setSignName(projectProperties.getAliSms().getSignName());
			// SMS_144146687
			request.setTemplateCode(templateCode);
			request.setTemplateParam(JSONUtil.writeValueAsString(paramMap));
			SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
			if (sendSmsResponse.getCode() != null && "OK".equals(sendSmsResponse.getCode())) {
				LOGGER.info("sms send success!");
				return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, "短信发送成功");
			}
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, "短信发送失败");
	}

	public static void main(String[] args) {
		// Map<String, Object> tempalte = Maps.newHashMap();
		// tempalte.put("DeviceName", "1");
		// tempalte.put("DeviceID", "2");
		// tempalte.put("temp", "3");
		// tempalte.put("rh", "4");
		// tempalte.put("isHot", "5");
		// tempalte.put("error", "6");
		//
		// String phoneNums = "15712030165";
		// String templateCode = "SMS_144146687";
		// SMSUtil.sendSms(phoneNums, templateCode, tempalte);
	}
}
